package com.qf.interceptor;

import com.qf.utils.JwtUtils;
import com.qf.vo.UserActionVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Component
public class UserActionInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 获取token
        String token = request.getHeader("token");
        // 从token中获取 用户名 （token颁发给谁的）
        String username = JwtUtils.getUserName(token);

        // 需要记录的用户访问行为
        UserActionVo userActionVo = new UserActionVo();
        userActionVo.setTime(new Date());
        userActionVo.setPath(request.getRequestURI());
        userActionVo.setName(username);

        // 将用户行为写入redis的list中
        String key = "history:"+username;
        redisTemplate.opsForList()
                .rightPush(key,userActionVo);

        return true;
    }
}
